/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FileChooser.java
 *
 * Created on Oct 4, 2011, 4:54:52 PM
 */
package redclient.ui;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author Isaias
 */
public class FileChooser extends javax.swing.JFrame {

    private int row = 0;
    /** Creates new form FileChooser */
    
    private javax.swing.JFrame self = null;
    
    private List<String> descs;
    
    private Map<Integer, List<Component>> myComponents;
    
    public FileChooser() {
        initComponents();
        myComponents = new HashMap<Integer, List<Component>>();
        myComponents.put(2, new ArrayList<Component>());
        final Container contentPane = this.getContentPane();
        contentPane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(5,5,15,5);
        contentPane.add(new JLabel("Files"), c);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 9;
        c.gridy = 0;
        c.insets = new Insets(5,5,15,5);
        JButton btnAddNew = new JButton("Add another file");
        btnAddNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_add.png")));
        contentPane.add(btnAddNew, c);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 10;
        c.gridy = 0;
        c.insets = new Insets(5,5,15,5);
        JButton btnOk = new JButton("OK");
        btnOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_ok_16px.png")));
        contentPane.add(btnOk, c);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 0;
        c.gridwidth = 3;
        c.gridy = 2;
        JTextField fileName = new JTextField("", 40);
        fileName.setName("path");
        fileName.setEditable(false);
        contentPane.add(fileName, c);
        myComponents.get(2).add(fileName);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 3;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton btnFile = new JButton("File");
        btnFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_file_browse.png")));
        contentPane.add(btnFile, c);
        myComponents.get(2).add(btnFile);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 4;
        c.gridy = 2;
        c.gridwidth = 2;
        JLabel optDesc = new JLabel("Optional description"); 
        contentPane.add(optDesc, c);
        myComponents.get(2).add(optDesc);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 6;
        c.gridy = 2;
        c.gridwidth = 4;
        JTextField txtDesc = new JTextField("", 40);
        contentPane.add(txtDesc, c);
        myComponents.get(2).add(txtDesc);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 10;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton btnDelete =  new JButton();
        btnDelete.setText(null);
        btnDelete.setToolTipText("Remove");
        btnDelete.setName("2");
        myComponents.get(2).add(btnDelete);
        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_remove_file.png"))); // NOI18N
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                JButton button = (JButton)e.getSource();
                Integer index = Integer.valueOf(button.getName());
                for(Component c : myComponents.get(index))
                {
                    contentPane.remove(c);
                }
                myComponents.remove(index);
                contentPane.validate();
                FileChooser.this.pack();
            }
        });
        contentPane.add(btnDelete, c);
        
        this.pack();
        
        row = 3;
        
        btnAddNew.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addNewFileInputs();
            }
        });
        
        btnFile.addActionListener(new FileHandler(fileName));
        
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FileChooser.this.setVisible(false);
            }
        });
    }
    
    public File[] getSelectedFiles()
    {
        List<File> files = null;
        
        boolean processDesc = false;
        
        for(Component c : this.getContentPane().getComponents())
        {
            if( c instanceof JTextField )
            {
                JTextField field = (JTextField)c;
                if( "path".equals(field.getName()) && !"".equals(field.getText().trim()) )
                {
                    if( files == null )
                    {
                        files = new ArrayList<File>();
                        descs = new ArrayList<String>();
                    }
                    File file = new File(field.getText());
                    if( ! file.exists() )
                    {
                        JOptionPane.showMessageDialog(self, String.format("File [%s] does not exist", file.getName()), "Non existent file", JOptionPane.ERROR_MESSAGE);
                    }
                    else if( ! file.canRead() )
                    {
                        JOptionPane.showMessageDialog(self, String.format("You have not read access to file [%s]", file.getName()), "Insuficcient privileges", JOptionPane.ERROR_MESSAGE);
                    }
                    else
                    {
                        files.add(file);
                        processDesc = true;
                    }
                }
                else if (processDesc)
                {
                    processDesc = false;
                    descs.add(field.getText());
                }
            }
        }
        return files == null ? null : files.toArray(new File[]{});
    }

    public String[] getDescriptions()
    {
        return descs == null ? null : descs.toArray(new String[]{});
    }
    
    private void addNewFileInputs()
    {
        final Container contentPane = this.getContentPane();
        GridBagConstraints c = new GridBagConstraints();
        myComponents.put(row, new ArrayList<Component>());
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridwidth = 3;
        c.gridy = row;
        c.insets = new Insets(5,5,5,5);
        JTextField fileName = new JTextField("", 40);
        fileName.setName("path");
        fileName.setEditable(false);
        contentPane.add(fileName, c);
        myComponents.get(row).add(fileName);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 3;
        c.gridy = row;
        c.gridwidth = 1;
        JButton btnFile =  new JButton("File");
        btnFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_file_browse.png")));
        contentPane.add(btnFile, c);
        myComponents.get(row).add(btnFile);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 4;
        c.gridy = row;
        c.gridwidth = 2;
        JLabel optDesc = new JLabel("Optional description");
        contentPane.add(optDesc, c);
        myComponents.get(row).add(optDesc);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 6;
        c.gridy = row;
        c.gridwidth = 4;
        JTextField txtOptDesc = new JTextField("", 40);
        contentPane.add(txtOptDesc, c);
        myComponents.get(row).add(txtOptDesc);
        
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5,5,5,5);
        c.gridx = 10;
        c.gridy = row;
        c.gridwidth = 1;
        JButton btnDelete =  new JButton();
        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/redclient/ui/img/button_remove_file.png"))); // NOI18N
        btnDelete.setName(String.valueOf(row));
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                JButton button = (JButton)e.getSource();
                Integer index = Integer.valueOf(button.getName());
                for(Component c : myComponents.get(index))
                {
                    contentPane.remove(c);
                }
                myComponents.remove(index);
                contentPane.validate();
                FileChooser.this.pack();
            }
        });

        contentPane.add(btnDelete, c);
        
        myComponents.get(row).add(btnDelete);
        
        this.pack();
        row++;
        
        btnFile.addActionListener(new FileHandler(fileName));
        
        
    }

    class FileHandler implements java.awt.event.ActionListener
    {
        private JTextField textField;
        
        FileHandler(JTextField textField)
        {
            this.textField = textField;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
                        final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = fc.showOpenDialog(textField.getParent());
            if( returnVal == JFileChooser.APPROVE_OPTION )
            {
                File file = fc.getSelectedFile();
                if( ! file.exists() )
                {
                    JOptionPane.showMessageDialog(self, String.format("File [%s] does not exist", file.getName()), "Non existent file", JOptionPane.ERROR_MESSAGE);
                }
                else if( ! file.canRead() )
                {
                    JOptionPane.showMessageDialog(self, String.format("You have not read access to file [%s]", file.getName()), "Insuficcient privileges", JOptionPane.ERROR_MESSAGE);
                }
                else
                {
                    textField.setText(fc.getSelectedFile().getAbsolutePath());
                }
            }
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 729, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 419, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FileChooser().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFrame jFrame1;
    // End of variables declaration//GEN-END:variables
}
